import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/Home/HomePage'
    },
    {
      path: '/Home/Analysis/',
      redirect: '/Home/Analysis/page1'
    },
    {
      path: '/Home',
      name: 'Home',
      component: HomeView,
      children: [
        {
          path: 'HomePage',
          name: 'HomePage',
          component: () => import("@/components/Home/HomePage.vue"),
        },
        {
          path: 'User',
          name: 'User',
          component: () => import("@/components/User/UserPage.vue"),
        },
        {
          path: 'Analysis',
          name: 'Analysis',
          component: () => import("@/components/Analysis/AnalysisPage.vue"),
          children: [
            {
              path: 'page1',
              name: 'page1',
              component: () => import("@/components/Analysis/Item/page1.vue"),
              props: (route) => ({ q: route.query.q || 0 })
            },
            {
              path: 'page2',
              name: 'page2',
              component: () => import("@/components/Analysis/Item/page2.vue"),
              props: (route) => ({ q: route.query.q || 1 })
            },
          ]
        },
      ]
    },
  ],
})

const targetPages = ['page1', 'page2'];

router.beforeEach((to, from, next) => {
  // 检查目标路由是否匹配 /Home/Bazaar/page[1-2]
  const matchedPage = targetPages.find(page => to.path === `/Home/Analysis/${page}`);

  if (matchedPage && !to.query.a) {
    // 如果匹配到目标页面并且 URL 中没有 a 参数
    const defaultParamValue = targetPages.indexOf(matchedPage); // 根据页面索引设置默认参数值

    next({
      path: to.path,
      query: { ...to.query, a: defaultParamValue }
    });
  } else {
    next();
  }
});

export default router
